package com.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.*;

import com.bdd.ConMySql;
import com.central.ServerThreadCentral;
import com.request.Sql2Json;
import com.serverSite.Processing;
import com.sun.xml.internal.bind.v2.TODO;


@SuppressWarnings("serial")
public class TheServlet extends HttpServlet implements Runnable
{
	private String url;
	private String defaultLogin;
	private String defaultPassword;
	private String comingFrom;
	private HttpSession session;
	private int codeLivraison; // user postal code to know wich server to connect 

	public TheServlet() {
		super();
	}
	@Override
	public void run() {
		System.out.println("########### ERROR RUN");
	}
	public void init(){ //defaults params
		url = getServletConfig().getInitParameter("url");		
		defaultLogin = getServletConfig().getInitParameter("defaultLogin");
		defaultPassword = getServletConfig().getInitParameter("defaultPassword");
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException 
	{
		System.out.println("########### on est dans le doGet");
		comingFrom = req.getParameter("comingFrom"); //previous page
		System.out.println("########### comingFrom "+comingFrom);
		session = req.getSession(); //creating a session
		
		if (comingFrom == null){
			comingFrom = "start";
		}
		if(req.getMethod().toUpperCase().equals("GET")){
			// if first connection
			
			if (comingFrom.equals("start")){	
				req.setAttribute("Login",defaultLogin);
				req.setAttribute("Password",defaultPassword);
			}
			// if  other page
			else {//TODO test if this 'else' is needed (i don't think so)
				req.setAttribute("Login", session.getAttribute("Login"));
				req.setAttribute("Password", session.getAttribute("Password"));
			}
			getServletContext().getRequestDispatcher(url).forward(req, rep);
		}
		// at this moment we have to know the postal code of the customer
		else 
		{
			//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if POST method (ie  connected)
			if(comingFrom.equals("connection"))
			{		
				session.setAttribute("Login", req.getParameter("txtLogin"));//stores the login and password in the session
				session.setAttribute("Password", req.getParameter("txtPassword"));
				ArrayList<String> errors=new ArrayList<String>();
				
				//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% managing errors
				if((req.getParameter("txtLogin").length()==0)||(req.getParameter("txtLogin").equals("Login"))){
					errors.add("The field 'Login' is not valid");
				}
				if((req.getParameter("txtPassword").length()==0)||(req.getParameter("txtPassword").equals("**********"))){
					errors.add("The field 'Password' is not valid");
				}
				if(errors.size()!=0){
					req.setAttribute("errorList", errors);
					getServletContext().getRequestDispatcher("/WEB-INF/views/errors.jsp").forward(req, rep);
				}
				
				//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if there's no error => login != "Login" & password != "*******"
				else {
					try {
						// else if there's no error (not empty fields) => try identification login / password
						if (identification(req.getParameter("txtLogin"),req.getParameter("txtPassword")) == true){
							req.setAttribute("Login", session.getAttribute("Login"));
							req.setAttribute("Password", session.getAttribute("Password"));
							
							Sql2Json s2j = new Sql2Json();
							ConMySql con = new ConMySql("SpiceCentral");// gets product list for being displayed in the JSP
							String sql = "SELECT * FROM product;";
							ResultSet rs=con.select(sql);
							JSONArray jsonA = s2j.responseArray(rs);// gets the list of products
							req.setAttribute("array", jsonA);// set the list as an attribute for being used in the JSP
							
							getServletContext().getRequestDispatcher("/WEB-INF/views/order.jsp").forward(req, rep);
							System.out.println("########### ( location ) "+session.getAttribute("codeLivraison").getClass());
						}else{ // login  and password false
							getServletContext().getRequestDispatcher("/WEB-INF/views/errors.jsp").forward(req, rep);
						}
					}catch (SQLException e){
						e.printStackTrace();
					}catch (ClassNotFoundException e){
						e.printStackTrace();
					}catch (JSONException e){
						e.printStackTrace();
					}
				}
				/** if we are here, it' because we validated the form 
				 * so we just have to get all products, the sum of prices and the highest delivery delay
				 */
			}else if(comingFrom.equals("order")){
				/*
				String idProd = req.getParameter("productId");
				System.out.println("########### "+idProd);
				int quantity = Integer.parseInt(req.getParameter("qty"));
				System.out.println("########### ORDER TASK");
				System.out.println("########### "+quantity);
				System.out.println("########### variables    "+idProd+"     "+quantity+"         "+codeLivraison);
				JSONObject json=new JSONObject();
				try {
					json.put("idProd",idProd);
					json.put("quantity",quantity);
					json.put("codeLivraison", codeLivraison);
				} catch (JSONException e) {
					//Auto-generated catch block
					e.printStackTrace();
				}
				new Thread (new ServerThreadCentral(Integer.parseInt(req.getParameter("productId")),quantity,codeLivraison)).start();
				new Thread (new ServerThreadCentral(codeLivraison)).start();*/
				getServletContext().getRequestDispatcher("/WEB-INF/views/TestPosted.jsp").forward(req, rep);
			}
			//remet les bdd à 1000--0
			if(comingFrom.equals("raz")){
				Processing p = new Processing();
				p.raz();
			}
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException 
	{
		doGet(req,rep);
	}

	/**
	 * indentifaication method
	 * returns false if not autenticated
	 * @param Login
	 * @param Password
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public boolean identification(String Login, String Password) throws SQLException, ClassNotFoundException
	{
		boolean x = false;
		ConMySql con = new ConMySql("jdbc:mysql://localhost/","SpiceCentral","root", "root");
		String sql = "SELECT * FROM Clients WHERE (name='"+Login+"');";
		ResultSet rs = con.select(sql);
		if (rs != null){
			rs.first();
			if((rs.getString("password")).equals(Password)){
				x = true;
				codeLivraison=Integer.parseInt(rs.getString("codeLivraison"));
				session.setAttribute("codeLivraison",codeLivraison);
			}			
		}
		con.close();
		return x;
	}
}
